<?php

/**

 * 商品

 *

 *

 * * @网店运维 (c) 2015-2018  Inc. (http://www.shopwwi.com)
 * @license    http://www.shopwwi.c om
 * @link       交流群号：111731672
 * @since      网店运维提供技术支持 授权请购买shopnc授权

 */



//use Shopnc\Tpl;



defined('InShopNC') or exit('Access Invalid!');

class goodsControl extends mobileHomeControl{
    public function __construct() {
        parent::__construct();
        Language::read('store_goods_index');
    }



    /**

     * 商品列表

     */

    public function goods_listOp() {

        $model_goods = Model('goods');

        $model_search = Model('search');

        $_GET['is_book'] = 0;



        //查询条件

        $condition = array();

        // ==== 暂时不显示定金预售商品，手机端未做。  ====

        $condition['is_book'] = 0;

        // ==== 暂时不显示定金预售商品，手机端未做。  ====

        if(!empty($_GET['gc_id']) && intval($_GET['gc_id']) > 0) {

            $condition['gc_id'] = $_GET['gc_id'];

        } elseif (!empty($_GET['keyword'])) {

            $condition['goods_name|goods_jingle'] = array('like', '%' . $_GET['keyword'] . '%');

        } elseif (!empty($_GET['barcode'])) {

            $condition['goods_barcode'] = $_GET['barcode'];

        } elseif (!empty($_GET['b_id']) && intval($_GET['b_id'] > 0)) {

            $condition['brand_id'] = intval($_GET['b_id']);

        }



        //所需字段

        $fieldstr = "goods_id,goods_commonid,store_id,goods_name,goods_jingle,store_name,goods_price,is_own_shop,goods_promotion_price,goods_promotion_type,goods_marketprice,goods_image,goods_salenum,evaluation_good_star,evaluation_count";



        // 添加3个状态字段

        $fieldstr .= ',is_virtual,is_presell,is_fcode,have_gift';



        //排序方式

        $order = $this->_goods_list_order($_GET['key'], $_GET['order']);



        //优先从全文索引库里查找

        list($goods_list,$indexer_count) = $model_search->indexerSearch($_GET,$this->page);

        if (!is_null($goods_list)) {

            $goods_list = array_values($goods_list);

            pagecmd('setEachNum',$this->page);

            pagecmd('setTotalNum',$indexer_count);

        } else {

            $goods_list = $model_goods->getGoodsListByColorDistinct($condition, $fieldstr, $order, $this->page);

        }

        $page_count = $model_goods->gettotalpage();

        //处理商品列表(团购、限时折扣、商品图片)

        $goods_list = $this->_goods_list_extend($goods_list);

        output_data(array('goods_list' => $goods_list), mobile_page($page_count));

    }



    /**

     * 商品列表排序方式

     */

    private function _goods_list_order($key, $order) {

        $result = 'is_own_shop desc,goods_id desc';

        if (!empty($key)) {



            $sequence = 'desc';

            if($order == 1) {

                $sequence = 'asc';

            }



            switch ($key) {

                //销量

                case '1' :

                    $result = 'goods_salenum' . ' ' . $sequence;

                    break;

                //浏览量

                case '2' :

                    $result = 'goods_click' . ' ' . $sequence;

                    break;

                //价格

                case '3' :

                    $result = 'goods_price' . ' ' . $sequence;

                    break;

            }

        }

        return $result;

    }



    /**

     * 处理商品列表(团购、限时折扣、商品图片)

     */

    private function _goods_list_extend($goods_list) {

        //获取商品列表编号数组

        $goodsid_array = array();

        foreach($goods_list as $key => $value) {

            $goodsid_array[] = $value['goods_id'];

        }

        

        $sole_array = Model('p_sole')->getSoleGoodsList(array('goods_id' => array('in', $goodsid_array)));

        $sole_array = array_under_reset($sole_array, 'goods_id');



        foreach ($goods_list as $key => $value) {

            $goods_list[$key]['sole_flag']      = false;

            $goods_list[$key]['group_flag']     = false;

            $goods_list[$key]['xianshi_flag']   = false;

            if (!empty($sole_array[$value['goods_id']])) {

                $goods_list[$key]['goods_price'] = $sole_array[$value['goods_id']]['sole_price'];

                $goods_list[$key]['sole_flag'] = true;

            } else {

                $goods_list[$key]['goods_price'] = $value['goods_promotion_price'];

                switch ($value['goods_promotion_type']) {

                    case 1:

                        $goods_list[$key]['group_flag'] = true;

                        break;

                    case 2:

                        $goods_list[$key]['xianshi_flag'] = true;

                        break;

                }

                

            }



            //商品图片url

            $goods_list[$key]['goods_image_url'] = cthumb($value['goods_image'], 360, $value['store_id']);



            unset($goods_list[$key]['goods_promotion_type']);

            unset($goods_list[$key]['goods_promotion_price']);

            unset($goods_list[$key]['store_id']);

            unset($goods_list[$key]['goods_commonid']);

            unset($goods_list[$key]['nc_distinct']);

        }



        return $goods_list;

    }



    /**

     * 商品详细页

     */

    public function goods_detailOp() {

        $goods_id = intval($_GET ['goods_id']);

        // 商品详细信息
        $model_goods = Model('goods');
        $goods_detail = $model_goods->getGoodsDetail($goods_id);
        if (empty($goods_detail)) {
            output_error('商品不存在');
        }

        // 默认预订商品不支持手机端显示

       if ($goods_detail['is_book']) {
            output_error('预订商品不支持手机端显示');
        }



        //推荐商品

        $model_store = Model('store');
        $hot_sales = $model_store->getHotSalesList($goods_detail['goods_info']['store_id'], 6, true);
        $goodsid_array = array();
        foreach($hot_sales as $value) {
           $goodsid_array[] = $value['goods_id'];
        }

        $sole_array = Model('p_sole')->getSoleGoodsList(array('goods_id' => array('in', $goodsid_array)));
        $sole_array = array_under_reset($sole_array, 'goods_id');
        $goods_commend_list = array();
        foreach($hot_sales as $value) {

           $goods_commend = array();
            $goods_commend['goods_id'] = $value['goods_id'];
            $goods_commend['goods_name'] = $value['goods_name'];
			$goods_commend['goods_jingle'] = $value['goods_jingle'];
            $goods_commend['goods_price'] = $value['goods_price'];
            $goods_commend['goods_promotion_price'] = $value['goods_promotion_price'];
            if (!empty($sole_array[$value['goods_id']])) {

                $goods_commend['goods_promotion_price'] = $sole_array[$value['goods_id']]['sole_price'];

            }

            $goods_commend['goods_image_url'] = cthumb($value['goods_image'], 240);

            $goods_commend_list[] = $goods_commend;

        }

        

        $goods_detail['goods_commend_list'] = $goods_commend_list;

        $store_info = $model_store->getStoreInfoByID($goods_detail['goods_info']['store_id']);



        $goods_detail['store_info']['store_id'] = $store_info['store_id'];

        $goods_detail['store_info']['store_name'] = $store_info['store_name'];

        $goods_detail['store_info']['member_id'] = $store_info['member_id'];

        $goods_detail['store_info']['member_name'] = $store_info['member_name'];

        $goods_detail['store_info']['avatar'] = getMemberAvatarForID($store_info['member_id']);



        $goods_detail['store_info']['goods_count'] = $store_info['goods_count'];



        if ($store_info['is_own_shop']) {

            $goods_detail['store_info']['store_credit'] = array(

                'store_desccredit' => array (

                    'text' => '描述',

                    'credit' => 5,

                    'percent' => '----',

                    'percent_class' => 'equal',

                    'percent_text' => '平',

                ),

                'store_servicecredit' => array (

                    'text' => '服务',

                    'credit' => 5,

                    'percent' => '----',

                    'percent_class' => 'equal',

                    'percent_text' => '平',

                ),

                'store_deliverycredit' => array (

                    'text' => '物流',

                    'credit' => 5,

                    'percent' => '----',

                    'percent_class' => 'equal',

                    'percent_text' => '平',

                ),

            );

        } else {

            $storeCredit = array();

            $percentClassTextMap = array(

                'equal' => '平',

                'high' => '高',

                'low' => '低',

            );

            foreach ((array) $store_info['store_credit'] as $k => $v) {

                $v['percent_text'] = $percentClassTextMap[$v['percent_class']];

                $storeCredit[$k] = $v;

            }

            $goods_detail['store_info']['store_credit'] = $storeCredit;

        }



        //商品详细信息处理

        $goods_detail = $this->_goods_detail_extend($goods_detail);



        // 如果已登录 判断该商品是否已被收藏

        if ($memberId = $this->getMemberIdIfExists()) {

            $c = (int) Model('favorites')->getGoodsFavoritesCountByGoodsId($goods_id, $memberId);

            $goods_detail['is_favorate'] = $c > 0;

            $goods_detail['cart_count'] = Model('cart')->countCartByMemberId($memberId);

        }



        output_data($goods_detail);

    }



    /**

     * 商品详细信息处理

     */

    private function _goods_detail_extend($goods_detail) {

        //整理商品规格

        unset($goods_detail['spec_list']);

        $goods_detail['spec_list'] = $goods_detail['spec_list_mobile'];

        unset($goods_detail['spec_list_mobile']);



        //整理商品图片

        unset($goods_detail['goods_image']);

        $goods_detail['goods_image'] = implode(',', $goods_detail['goods_image_mobile']);

        unset($goods_detail['goods_image_mobile']);



        //商品链接

        $goods_detail['goods_info']['goods_url'] = urlShop('goods', 'index', array('goods_id' => $goods_detail['goods_info']['goods_id']));



        //整理数据

        unset($goods_detail['goods_info']['goods_commonid']);

        unset($goods_detail['goods_info']['gc_id']);

        unset($goods_detail['goods_info']['gc_name']);

        unset($goods_detail['goods_info']['store_id']);

        unset($goods_detail['goods_info']['store_name']);

        unset($goods_detail['goods_info']['brand_id']);

        unset($goods_detail['goods_info']['brand_name']);

        unset($goods_detail['goods_info']['type_id']);

        unset($goods_detail['goods_info']['goods_image']);

        unset($goods_detail['goods_info']['goods_body']);

        unset($goods_detail['goods_info']['goods_state']);

        unset($goods_detail['goods_info']['goods_stateremark']);

        unset($goods_detail['goods_info']['goods_verify']);

        unset($goods_detail['goods_info']['goods_verifyremark']);

        unset($goods_detail['goods_info']['goods_lock']);

        unset($goods_detail['goods_info']['goods_addtime']);

        unset($goods_detail['goods_info']['goods_edittime']);

        unset($goods_detail['goods_info']['goods_selltime']);

        unset($goods_detail['goods_info']['goods_show']);

        unset($goods_detail['goods_info']['goods_commend']);

        unset($goods_detail['goods_info']['explain']);

        unset($goods_detail['goods_info']['cart']);

        unset($goods_detail['goods_info']['buynow_text']);

        unset($goods_detail['groupbuy_info']);

        unset($goods_detail['xianshi_info']);



        return $goods_detail;

    }



    /**

     * 商品详细页

     */

    public function goods_bodyOp() {
        if(empty($_COOKIE['key'])){
            $member_name = $_SESSION['member_name'];
            $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0,999999)));
            setcookie('key',$token,time()+3600*24*365,"/");
        }

        header("Access-Control-Allow-Origin:*");
        $goods_id = intval($_GET['goods_id']);

        // 商品详细信息
        $model_goods = Model('goods');
        $goods_detail = $model_goods->getGoodsDetail($goods_id);
        $goods_info = $goods_detail['goods_info'];
        if (empty($goods_info)) {
            showMessage(L('goods_index_no_goods'), '', 'html', 'error');
        }
        $model_store = Model('store');
        $model_store->getStoreInfo($goods_info['store_id'], $goods_info);
//        echo $goods_info['store_id'];

        // 看了又看（同分类本店随机商品）
        $size = $goods_info['is_own_shop'] ? 4 : 4;
        $goods_rand_list = $model_goods->getGoodsGcStoreRandList($goods_info['gc_id_1'], $goods_info['store_id'], $goods_info['goods_id'], $size);
        Tpl::output('goods_rand_list', $goods_rand_list);

        Tpl::output('spec_list', $goods_detail['spec_list']);
        Tpl::output('spec_image', $goods_detail['spec_image']);
        Tpl::output('goods_image', $goods_detail['goods_image']);
        Tpl::output('mansong_info', $goods_detail['mansong_info']);
        Tpl::output('gift_array', $goods_detail['gift_array']);

        // 浏览过的商品
        $viewed_goods = Model('goods_browse')->getViewedGoodsList($_SESSION['member_id'], 20);
        Tpl::output('viewed_goods', $viewed_goods);

        // 生成缓存的键值
        $hash_key = $goods_info['goods_id'];
        $_cache = rcache($hash_key, 'product');
        if (empty($_cache)) {
            // 查询SNS中该商品的信息
            $snsgoodsinfo = Model('sns_goods')->getSNSGoodsInfo(array('snsgoods_goodsid' => $goods_info['goods_id']), 'snsgoods_likenum,snsgoods_sharenum');
            $_cache = array();
            $_cache['likenum'] = $snsgoodsinfo['snsgoods_likenum'];
            $_cache['sharenum'] = $snsgoodsinfo['snsgoods_sharenum'];
            // 缓存商品信息
            wcache($hash_key, $_cache, 'product');
        }
        $goods_info = array_merge($goods_info, $_cache);

        $inform_switch = true;
        // 检测商品是否下架,检查是否为店主本人
        if ($goods_info['goods_state'] != 1 || $goods_info['goods_verify'] != 1 || $goods_info['store_id'] == $_SESSION['store_id']) {
            $inform_switch = false;
        }
        Tpl::output('inform_switch',$inform_switch );

        // 如果使用运费模板
        if ($goods_info['transport_id'] > 0) {
            // 取得三种运送方式默认运费
            $model_transport = Model('transport');
            $transport = $model_transport->getExtendList(array('transport_id' => $goods_info['transport_id']));
            if (!empty($transport) && is_array($transport)) {
                foreach ($transport as $v) {
                    $goods_info[$v['type'] . "_price"] = $v['sprice'];
                }
            }
        }
        // 验证预定商品是否到期
        if ($goods_info['is_book'] == 1) {
            if ( $goods_info['book_down_time'] < TIMESTAMP ) {
                QueueClient::push('updateGoodsPromotionPriceByGoodsId', $goods_info['goods_id']);
                $goods_info['is_book'] = 0;
            } else {
                $remain_time = intval($goods_info['book_down_time'])- TIMESTAMP; //剩余的时间
                $remain_day = floor($remain_time/(60*60*24)); //剩余的天数
                $remain_hour = floor(($remain_time - $remain_day*60*60*24)/(60*60)); //剩余的小时数
                $remain_minute = floor(($remain_time - $remain_day*60*60*24 - $remain_hour*60*60)/60); //剩余的分钟数
                Tpl::output('remain', array('day' => $remain_day, 'hour' => $remain_hour, 'minute' => $remain_minute));
            }
        }
        //处理商品消费者保障服务信息
        $goods_list = $model_goods->getGoodsContract(array(0=>$goods_info));
        $goods_info = $goods_list[0];
        Tpl::output('goods', $goods_info);
        $model_plate = Model('store_plate');
        // 顶部关联版式
        if ($goods_info['plateid_top'] > 0) {
            $plate_top = $model_plate->getStorePlateInfoByID($goods_info['plateid_top']);
            Tpl::output('plate_top', $plate_top);
        }
        // 底部关联版式
        if ($goods_info['plateid_bottom'] > 0) {
            $plate_bottom = $model_plate->getStorePlateInfoByID($goods_info['plateid_bottom']);
            Tpl::output('plate_bottom', $plate_bottom);
        }
        Tpl::output('store_id', $goods_info['store_id']);

        //推荐商品
        $goods_commend_list = $model_goods->getGoodsCommendList($goods_info['store_id'], 4);
        Tpl::output('goods_commend',$goods_commend_list);

        // 当前位置导航
        $nav_link_list = Model('goods_class')->getGoodsClassNav($goods_info['gc_id'], 0);
        $nav_link_list[] = array('title' => $goods_info['goods_name']);
        Tpl::output('nav_link_list', $nav_link_list);

        //评价信息
        $goods_evaluate_info = Model('evaluate_goods')->getEvaluateGoodsInfoByGoodsID($goods_id);
        Tpl::output('goods_evaluate_info', $goods_evaluate_info);

        $seo_param = array();
        $seo_param['name'] = $goods_info['goods_name'];
        $seo_param['key'] = $goods_info['goods_keywords'];
        $seo_param['description'] = $goods_info['goods_description'];
        Model('seo')->type('product')->param($seo_param)->show();
        Tpl::showpage('goods_body');
    }

}

